package com.haojiang.mh.remote.ui.frag

import android.text.TextUtils
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import cn.com.heaton.blelibrary.ble.utils.ThreadUtils
import com.haojiang.mh.R
import com.haojiang.mh.remote.adapter.ControlFragAdapter
import com.haojiang.mh.remote.adapter.FragStateAdapter
import com.haojiang.mh.remote.base.BaseFrag
import com.haojiang.mh.remote.bean.ControlLeftMenuBean
import com.haojiang.mh.remote.bean.FragBean
import com.haojiang.mh.remote.enums.EArea
import com.haojiang.mh.remote.enums.EAreaMenu
import com.haojiang.mh.remote.enums.EConnect
import com.haojiang.mh.remote.enums.EStep
import com.haojiang.mh.remote.event.*
import com.haojiang.mh.remote.ui.dialog.BleSingleDialogFrag
import com.haojiang.mh.remote.ui.dialog.SelecBedDialogFrag
import com.haojiang.mh.remote.ui.dialog.SelectControlDialogFrag
import com.haojiang.mh.remote.ui.dialog.SelectGroupDialogFrag
import com.haojiang.mh.remote.utils.*
import com.haojiang.mh.remote.utils.BleUtil.Companion.ble
import com.haojiang.mh.remote.utils.BleUtil.Companion.devDisconnectAll
import com.haojiang.mh.remote.utils.BleUtil.Companion.isDevConncted
import com.haojiang.mh.remote.utils.BleUtil.Companion.lastConnect
import com.haojiang.mh.remote.utils.BleUtil.Companion.prepareConnect
import com.haojiang.mh.remote.utils.Constant.RX_HAS_ALARM
import com.haojiang.mh.remote.utils.Constant.RX_HAS_AROMA
import com.haojiang.mh.remote.utils.Constant.RX_HAS_LED
import com.haojiang.mh.remote.utils.MenuUtil.setFunctionList
import com.lx.permission.IPermissionCallback
import com.lx.permission.PermissionManager
import kotlinx.android.synthetic.main.frag_control.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit


class ControlFrag : BaseFrag() {

    private var itemSearch: MenuItem? = null
    private var itemBleStatus: MenuItem? = null
    private var itemBleScan: MenuItem? = null

    private val controlFragAdapter by lazy { ControlFragAdapter() }     //左边的选项

    private val fragSubList = arrayListOf<FragBean>(
        FragBean(EArea.MOTOR.key, MotorFrag()),
        FragBean(EArea.MASSAGE.key, MassageFrag()),
        FragBean(EArea.MEMORY.key, MemoryFrag()),
        FragBean(EArea.ALARM.key, AlarmFrag()),
        FragBean(EArea.LED.key, LedFrag()),
        FragBean(EArea.AROMA.key, AromaFrag()),
        FragBean(EArea.SLEEP.key, SleepFrag()),

//        FragBean(EArea.NEW_MOTOR.key, MotorNewFrag()),
//        FragBean(EArea.NEW_MEMORY.key, MemoryNewFrag()),
//        FragBean(EArea.NEW_MASSAGE.key, MassageNewFrag()),
//        FragBean(EArea.NEW_ALARM.key, AlarmNewFrag()),
    )

    private val fragStateAdapter by lazy {
        FragStateAdapter(
            activity!!,
            fragSubList
        )
    }    //右边的控制fragment
    private val menuList: MutableList<ControlLeftMenuBean> = mutableListOf()


    private val mIPermissionCallback = IPermissionCallback {
        BleSingleDialogFrag.show(activity!!)
//        ThreadUtils.asyn {
//            Thread.sleep(800)
//            ThreadUtils.ui {
//                BleSingleDialogFrag.show(activity!!)
//            }
//        }
    }

    val iMenuItemClickListener: ControlFragAdapter.IMenuItemClickListener =
        object : ControlFragAdapter.IMenuItemClickListener {
            override fun onItemClick(controlLeftMenuBean: ControlLeftMenuBean, position: Int) {
                setSurfaceName(controlLeftMenuBean.code)
                when (controlLeftMenuBean.code) {

                    EArea.MOTOR.key -> {
                        controlViewPager2.setCurrentItem(EAreaMenu.MOTOR.key, false)
                    }
                    EArea.MASSAGE.key -> {
                        controlViewPager2.setCurrentItem(EAreaMenu.MASSAGE.key, false)
                    }
                    EArea.MEMORY.key -> {
                        controlViewPager2.setCurrentItem(EAreaMenu.MEMORY.key, false)
                    }
                    EArea.ALARM.key -> {
                        controlViewPager2.setCurrentItem(EAreaMenu.ALARM.key, false)
                    }
                    EArea.LED.key -> {
                        controlViewPager2.setCurrentItem(EAreaMenu.LED.key, false)
                    }
                    EArea.AROMA.key -> {
                        controlViewPager2.setCurrentItem(EAreaMenu.AROMA.key, false)
                    }
                    EArea.SLEEP.key -> {
                        controlViewPager2.setCurrentItem(EArea.SLEEP.key, false)
                    }

//                    EArea.NEW_MOTOR.key -> {
//                        controlViewPager2.setCurrentItem(EAreaMenu.NEW_MOTOR.key, false)
//                    }
//                    EArea.NEW_MEMORY.key -> {
//                        controlViewPager2.setCurrentItem(EAreaMenu.NEW_MEMORY.key, false)
//                    }
//                    EArea.NEW_MASSAGE.key -> {
//                        controlViewPager2.setCurrentItem(EAreaMenu.NEW_MASSAGE.key, false)
//                    }
//                    EArea.NEW_ALARM.key -> {
//                        controlViewPager2.setCurrentItem(EAreaMenu.NEW_ALARM.key, false)
//                    }

                    else -> {
                    }
                }
            }
        }

    override fun onLayoutId(): Int {
        return R.layout.frag_control
    }

    override fun initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun initListener() {
        setHasOptionsMenu(true)
        (activity as AppCompatActivity?)?.setSupportActionBar(controlToolbar)
        (activity as AppCompatActivity?)?.supportActionBar?.let {
            it.setDisplayHomeAsUpEnabled(true)
            it.setHomeAsUpIndicator(R.drawable.ic_menu)
        }

        //初始化recycleview
        val layoutManager = LinearLayoutManager(context)
        rvMenu.layoutManager = layoutManager
        //设置adapter
        rvMenu.adapter = controlFragAdapter
        //设置菜单点击回调函数
        controlFragAdapter.setOnMenuItemClickListener(iMenuItemClickListener)
        controlViewPager2.offscreenPageLimit = MenuUtil.menuMap.size
        controlViewPager2.adapter = fragStateAdapter
        controlViewPager2.isUserInputEnabled = false              //进制controlViewPager2滑动
    }


    override fun initData() {
//        lastConnect.fragMainList.add(EArea.MOTOR.key)
//        lastConnect.fragMainList.add(EArea.MASSAGE.key)
//        lastConnect.fragMainList.add(EArea.MEMORY.key)
//        lastConnect.fragMainList.add(EArea.ALARM.key)
        lastConnect.fragMainList.add(EArea.SLEEP.key)
        setMenuList(lastConnect.fragMainList)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
//        iControlFragPresenter.releaseView()
    }


    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.toolbar_control, menu)
        itemSearch = menu.findItem(R.id.itemSearch)
        itemBleStatus = menu.findItem(R.id.itemBleStatus)
        itemBleScan = menu.findItem(R.id.itemBleScan)
    }

    override fun onPrepareOptionsMenu(menu: Menu) {
        if (isDevConncted()) {
            if (isDevConncted()) {
                itemBleStatus!!.setIcon(ContextCompat.getDrawable(context, R.drawable.ic_ble_p))
                itemBleStatus!!.title = getString(R.string.f_connect)
            } else {
                itemBleStatus!!.setIcon(ContextCompat.getDrawable(context, R.drawable.ic_ble_n))
                itemBleStatus!!.title = getString(R.string.f_disconnect)
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {

            android.R.id.home -> {
                EventBus.getDefault().post(DrawerEvent())
            }

            R.id.itemBleStatus -> {
                if (isDevConncted()) {
                    devDisconnectAll()
                    showToast(getString(R.string.m_device_is_disconnected))
                } else {
                    //如果是第一次连接
                    if (lastConnect.bleDeviceList.size <= 0) {
                        callSurface()
                    } else {
                        BleUtil.devReconnect()
                    }
                }
            }

            R.id.itemBleScan -> {
                callSurface()
            }

            R.id.itemSearch -> {
                searchSurface()
            }
        }
        return true
    }

    //搜索遥控器界面
    private fun searchSurface() {
        if (ble.isBleEnable) {
            if (isDevConncted()) {
                if (lastConnect.connectType == EConnect.CONNECT_SINGLE.data) {                     //当前连接是单个设备连接
                    SelectControlDialogFrag.show(
                        activity!!,
                        lastConnect.bleDeviceList.get(0).bleAddress
                    )
                } else {
                    choiceSelectGroupFrag(
                        lastConnect.connectType,
                        lastConnect.connectId
                    )        //当前连接是组设备连接
                }
            } else {
                callSurface()
            }
        }
    }

    private fun callSurface() {
        if (!Util.checkBleStatus(activity!!)) return
        //申请权限
        PermissionManager.getInstance().setIPermissionCallback(mIPermissionCallback, 0)
        PermissionManager.getInstance().requestPermission(
            activity!!,
            BleUtil.permissionArr
        )
    }

    private fun choiceSelectGroupFrag(groupType: Int, groupId: Long) {
        when (Util.getPackageName()) {
            "com.richmat.richmat" -> {
                SelectGroupDialogFrag.show(activity!!, groupType, groupId)
            }
            "com.richmat.poshlavish" -> {
                SelecBedDialogFrag.show(activity!!, groupType, groupId)
            }
        }
    }

    //单一设备确定连接
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onConnectEvent(event: ConnectEvent) {
        if (event.connectType == EConnect.CONNECT_SINGLE.data) {
            if (event.connectStep == EStep.STEP_CLICK_CONNECT.data) {                                     //连接步骤-点击
                event.bleDeviceList.run {
                    prepareConnect(event.bleDeviceList)                    //准备连接
                    connectDeviceList(lastConnect.bleDeviceList.get(0).bleAddress)
                }
            } else if (event.connectStep == EStep.STEP_SELECT_INTERFACE.data) {
                connectDeviceList(lastConnect.bleDeviceList.get(0).bleAddress)
            }
        }
    }

    private fun connectDeviceList(bleAddress: String) {
        val surfaceNo =
            BleUtil.readSingleSurfaceNo(bleAddress)                                                                         //读取界面
        if (TextUtils.isEmpty(surfaceNo)) {
//            LogUtil.e("进入了关键点" + bleAddress)
            SelectControlDialogFrag.show(activity!!, bleAddress)
        } else {
            //获取界面的所有功能
//            val surfaceBean = SurfaceKey.keyMap.get(InterfaceNo.substring(0, 4).toUpperCase(Locale.ROOT))
//            if (surfaceBean != null && !InterfaceNo.equals(Constant.QRRM, ignoreCase = true)) {          //如果搜索的界面存在并且不能为公用界面QRRM
            val surface = BleUtil.getSurface(surfaceNo)
            if (surface != null && !surfaceNo.equals(
                    Constant.QRRM,
                    ignoreCase = true
                )
            ) {          //如果搜索的界面存在并且不能为公用界面QRRM
//                lastBleDeviceList.clear()
//                lastBleDeviceList.addAll(bleDeviceList)
//                LogUtil.e(lastBleDeviceList.size.toString() + "=单机连接数量")
//                lastConnect.isNew = true
                if (lastConnect.bleDeviceList.size > 0) {                                                                    //如果最后一次连接的蓝牙设备不为空
                    lastConnect.surface = surface                               //记录最后一次连接的界面详细信息
                    BleUtil.devConnects(lastConnect.bleDeviceList)                                                    //连接单个蓝牙设备
                    EventBus.getDefault()
                        .post(SurfaceEvent(surface))                                        //同时通知各个界面更新界面
                }
            } else {
                SelectControlDialogFrag.show(
                    activity!!,
                    bleAddress
                )                                                   //选择的界面不存在跳出界面继续选择
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRxMotorEvent(event: RxMotorEvent) {
        this.menuList.clear()
//        setNewMenuList(EArea.NEW_MOTOR.value)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBleEvent(event: BleEvent) {
        when (event.devStatus) {
//            BleStatus.CONNECT_ -> {
//                fragExtraList.clear()
//            }

            //已经连接但未获取到服务
            BleStatus.CONNECT_EXCEPTION -> {
                Util.hideLoading()
                showToast(getString(R.string.m_device_is_disconnected))
//                if (!BleUtil.keepAliveIsRun) {
//                }
            }

            BleStatus.GATT_CONNECT,
            BleStatus.CONNECT_TIME_OUT -> {
                Util.hideLoading()
            }
            BleStatus.DISCONNECT_PASSIVE -> {
                if (!isDevConncted()) {
                    itemBleStatus!!.setIcon(R.drawable.ic_ble_n)
                    itemBleStatus!!.title = getString(R.string.f_disconnect)
                }
            }

            BleStatus.GATT_SERVICE_CONNECT -> {
//                Util.hideLoading()
//                LogUtil.e("已经连接图片显示=" + itemBleStatus)
//                fragExtraList.clear()   //清除功能区
                itemBleStatus!!.setIcon(R.drawable.ic_ble_p)
                itemBleStatus!!.title = getString(R.string.f_connect)
            }
            BleStatus.GATT_SERVICE_DISCONNECT -> {
                showToast(getString(R.string.m_device_is_disconnected))
            }
            else -> {
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiverEvent(event: ReceiverEvent) {
        //判断是否含有闹钟、七彩灯、香薰区域功能
        lastConnect.surface?.let {
            when (event.rxData) {
                RX_HAS_ALARM -> {
                    LogUtil.e("含有闹钟")
//                if (lastConnect.hasAlarm && !lastConnect.fragExtraList.contains(EArea.ALARM.key)) {
//                    if (it.hasAlarm && !lastConnect.fragExtraList.contains(EArea.ALARM.key)) {
//                        lastConnect.fragExtraList.add(EArea.ALARM.key)
//                        addExtraFun(EArea.ALARM.key)
//                    }
                    if (it.alarmList != null) {
                        addExtraFun(EArea.ALARM.key)
                    }
                }

                RX_HAS_LED -> {
//                    if (it.hasLed && !lastConnect.fragExtraList.contains(EArea.LED.key)) {
//                        lastConnect.fragExtraList.add(EArea.LED.key)
//                        addExtraFun(EArea.LED.key)
//                    }
                    if (it.hasLed) {
                        addExtraFun(EArea.LED.key)
                    }
                }

                RX_HAS_AROMA -> {
//                    if (it.hasAroma && !lastConnect.fragExtraList.contains(EArea.AROMA.key)) {
//                        lastConnect.fragExtraList.add(EArea.AROMA.key)
//                        addExtraFun(EArea.AROMA.key)
//                    }
                    if (it.hasAroma) {
                        addExtraFun(EArea.AROMA.key)
                    }
                }
            }

        }
    }

    private fun addExtraFun(ExtraFun: Int) {
        if (!lastConnect.fragMainList.contains(ExtraFun)) {
            lastConnect.fragMainList.add(ExtraFun)
            if (lastConnect.fragMainList.contains(EArea.MOTOR.key)) {
                lastConnect.fragMainList.sort()
//                LogUtil.e("额外功能刷新了")
                setMenuList(lastConnect.fragMainList)
            }
        }
    }


    /**
     * 老协议
     * 完成选择界面后并携带界面功能即将进行刷新
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFunctionEvent(event: SurfaceEvent) {
        LogUtil.e(event.surface.funList.size.toString() + "==是否新协议==" + lastConnect.isNew)
        if (event.surface.funList.size > 0 && !lastConnect.isNew) { //老协议处理
//            lastConnect.hasAlarm = event.surface.hasAlarm
//            lastConnect.hasLed = event.surface.hasLed
//            lastConnect.hasAroma = event.surface.hasAroma
            lastConnect.fragMainList.clear()
            lastConnect.fragMainList.add(EArea.SLEEP.key)
            for (key in event.surface.funList) {
                val cmd = CmdUtil.viewMap.get(key)  //获取界面的主功能(左侧要显示的功能)(马达区，记忆位置区，按摩器，闹钟，七彩灯，香薰)
                cmd?.let {
                    when (it.erea) {
                        EArea.MOTOR.key -> {      //马达区
//                            LogUtil.e("马达区=进来新马达了" + lastConnect.isNew)

                            if (lastConnect.fragMainList.contains(EArea.MOTOR.key)) {
                            } else {
                                lastConnect.fragMainList.add(EArea.MOTOR.key)
                            }
                        }

                        EArea.MASSAGE.key -> {    //按摩器区
                            if (lastConnect.fragMainList.contains(EArea.MASSAGE.key)) {
                            } else {
                                lastConnect.fragMainList.add(EArea.MASSAGE.key)
                            }
                        }

                        EArea.MEMORY.key -> { //记忆位置区
                            if (lastConnect.fragMainList.contains(EArea.MEMORY.key)) {
                            } else {
                                lastConnect.fragMainList.add(EArea.MEMORY.key)
                            }
                        }

                        else -> {
                        }
                    }
                }
            }


//            LogUtil.e(lastConnect.fragMainList.size.toString() + "==主功能数量")
            setFunctionList(event.surface.funList) //保存功能准备给其他fragment初始化时用
//            lastConnect.fragExtraList.forEach {
//                if (!lastConnect.fragMainList.contains(it)) {
//                    lastConnect.fragMainList.add(it)
//                }
//            }
            lastConnect.fragMainList.sort()
            setMenuList(lastConnect.fragMainList)

        }
    }

    private fun setSurfaceName(surfaceCode: Int) {
        when (surfaceCode) {
            EArea.MOTOR.key -> {
                tvSurfaceName.setText(getString(R.string.f_surface_postion))
            }
            EArea.MASSAGE.key -> {
                tvSurfaceName.setText(getString(R.string.f_surface_massage))
            }
            EArea.MEMORY.key -> {
                tvSurfaceName.setText(getString(R.string.f_surface_memory))
            }
            EArea.ALARM.key -> {
                tvSurfaceName.setText(getString(R.string.f_surface_alarm))
            }
            EArea.LED.key -> {
                tvSurfaceName.setText(getString(R.string.f_surface_led))
            }
            EArea.AROMA.key -> {
                tvSurfaceName.setText(getString(R.string.f_surface_aroma))
            }
            EArea.SLEEP.key -> {
                tvSurfaceName.setText(getString(R.string.f_surface_sleep))
            }
            else -> {
            }
        }
    }

    //    fun setMenuList(list: MutableList<Int>): MutableList<HomeMenuItem> {
//    @Synchronized
    fun setMenuList(menuList: MutableList<Int>) {

//        val menuList: MutableList<HomeMenuItem> = mutableListOf()
        this.menuList.clear()
        for (index in 0..menuList.size - 1) {
            val controlMenuItem = MenuUtil.menuMap.get(menuList.get(index))
            controlMenuItem?.let {
                if (index == 0) setSurfaceName(it.code)
                if (!this.menuList.contains(controlMenuItem)) {
                    this.menuList.add(controlMenuItem)
                }
            }
        }
        controlFragAdapter.setData(this.menuList)

        ThreadUtils.submit {
            this.menuList.forEach {
                EventBus.getDefault().post(FunChangeEvent(it.code))
            }
            TimeUnit.MILLISECONDS.sleep(80)
            ThreadUtils.ui {
                if(this.menuList.size > 1) {
//                    controlViewPager2.setCurrentItem(0, false)
                    controlViewPager2.setCurrentItem(EAreaMenu.MOTOR.key, false)
                }else {
                    controlViewPager2.setCurrentItem(EArea.SLEEP.key, false)
                }
            }
        }
    }


//    @Synchronized
//    fun setNewMenuList(area: String) {
////        LogUtil.e("setNewMenuList")
//
//        var controlMenuItem: ControlLeftMenuBean? = null
//        when (area) {
//            EArea.NEW_MOTOR.value -> {
//                controlMenuItem = MenuUtil.menuMap.get(EArea.NEW_MOTOR.key)
//            }
//            EArea.NEW_MEMORY.value -> {
//                controlMenuItem = MenuUtil.menuMap.get(EArea.NEW_MEMORY.key)
//            }
//            EArea.NEW_MASSAGE.value -> {
//                controlMenuItem = MenuUtil.menuMap.get(EArea.NEW_MASSAGE.key)
//            }
//        }
//        controlMenuItem?.let {
//            if (!this.menuList.contains(controlMenuItem)) {
//                this.menuList.add(controlMenuItem)
//            }
//        }
////        LogUtil.e(this.menuList.size.toString()  + "=menulist")
//        controlFragAdapter.setData(this.menuList)
//
//        ThreadUtils.submit {
//            ThreadUtils.ui {
//                controlViewPager2.setCurrentItem(EAreaMenu.NEW_MOTOR.key, false)
//            }
//        }
//    }


    /**
     * 加载成功后回调
     */
//    override fun onLoadSuccess(list: List<ControlLeftMenuBean>?) {

//        if (list != null) {
//            LogUtil.e("主界面加载完毕")
////            ThreadUtils.asyn {
////                TimeUnit.MILLISECONDS.sleep(10000)
//            ThreadUtils.ui {
//                fragStateAdapter.setData(menuList)      //刷新右侧的功能界面 fragment
//                controlFragAdapter.setData(menuList)    //刷新左侧的功能界面 list
//
//                ThreadUtils.asynQueue {
//                    Thread.sleep(500)
//                    EventBus.getDefault().post(FunChangeEvent(viewPager2))
//                    Thread.sleep(300)
//                    ThreadUtils.ui {
//                        viewPager2.setCurrentItem(0)
//                    }
//                }
//            }
//            menuList.clear()
//            menuList.addAll(list)                       //左侧
//            fragStateAdapter.setData(menuList)      //刷新右侧的功能界面 fragment
//            homeFragAdapter.setData(menuList)    //刷新左侧的功能界面 list
//
//            ThreadUtils.asynQueue {
//                Thread.sleep(500)
//                EventBus.getDefault().post(FunChangeEvent(viewPager2))
//                Thread.sleep(300)
//                ThreadUtils.ui {
//                    viewPager2.setCurrentItem(0)
//                }
//            }
//        }

    //设置马达默认显示
//        getFragment(MOTOR)
//    }

//    override fun onLoadError(message: String?) {

//    }

//    override fun onLoadMore(list: List<ControlLeftMenuBean>?) {

//    }

}